#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
typedef int HpDataType;
typedef struct Heap
{
	HpDataType* a;
	int size;
	int capacity;
}Heap;
void HpInit(Heap* php);
void HpDestroy(Heap* php);
void HpPush(Heap* php, HpDataType x);
void HpPop(Heap* php);
HpDataType HpTop(Heap* php);
bool HpEmpty(Heap* php);
void HpInit(Heap* php)
{
	assert(php);
	php->a = NULL;
	php->size = php->capacity = 0;
}
void HpDestroy(Heap* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->size = php->capacity = 0;
}
void Swap(HpDataType* a, HpDataType* b)
{
	HpDataType tmp = *a;
	*a = *b;
	*b = tmp;
}

void AdjustUp(HpDataType* a,int n)
{
	assert(a);

	int child = n;
	int parent = (child - 1) / 2;

	while (child > 0)
	{
		if (a[child] < a[parent])
		{

			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;


		}
		else
		{
			break;
		}

	}



}

void HpPush(Heap* php, HpDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HpDataType* tmp = (HpDataType*)realloc(php->a, sizeof(HpDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	php->size++;
	AdjustUp(php,php->size-1);
}
void AdjustDown(HpDataType* a, int n)
{
	int parent = 0;
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] > a[child + 1])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}


	}
}

void HpPop(Heap* php)
{
	assert(php);
	assert(php->size);
	Swap(&php->a[php->size - 1], &php->a[0]);
	php->size--;
	AdjustDown(&php->a, php->size);

}
HpDataType HpTop(Heap* php)
{
	assert(php);
	assert(php->size);
	return php->a[0];
}


bool HpEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}
void heapsort(int* arr,int n)
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		AdjustUp(arr, i);
	}
	int end = n - 1;
	while (end > 0)
	{
		Swap(&arr[end], &arr[0]);
		AdjustDown(arr, end);
		end--;
	}
}

int main()
{
	int arr[10] = { 5,6,1,3,4,8,9,7,2,0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	 heapsort(arr,sz);
	 return 0;
}